package com.google.code.bankagregator.adapter.bank.imex.parser.deposit;

import com.google.code.bankagregator.adapter.exception.AdapterConnectException;
import com.google.code.bankagregator.entities.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created with IntelliJ IDEA.
 * User: kirill
 * Date: 14.06.13
 * Time: 5:27
 * To change this template use File | Settings | File Templates.
 */
public class ImexDepProfitParser {
    private static final String DEPOSIT_URL = "http://imexbank.com.ua/rus/all_deps.phtml#3w";
    private static final int B_NAME_INDEX = 1;
    private static final int TERM_INDEX = 0;
    private static final int TR_TERM_INDEX = 2;
    private static final int TR_MIN_AMOUNT_INDEX = 4;
    private static final int TD_UAH_RATE_INDEX = 2;
    private static final int TD_USD_RATE_INDEX = 3;
    private static final int TD_EUR_RATE_INDEX = 4;
    private Document con = null;
    private Bank bank = null;

    public ImexDepProfitParser() throws AdapterConnectException {
        bank = new Bank();
        bank.setName("АО \"ИМЭКСБАНК\"");
        bank.setUrl("http://imexbank.com.ua/rus/main.phtml");
        try {
            con = Jsoup.connect(DEPOSIT_URL).timeout(5000).get();
        } catch (IOException e) {
            throw new AdapterConnectException(e.getMessage());
        }
    }

    /**
     * Get UAH deposit`s params (Желаемая прибыль)
     *
     * @return UAH deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getUAHDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table[width=672]").select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").first();
        String minAmountStr = minAmountEl.text().substring(23, 29).replace(" ", "");
        int minAmount = Integer.parseInt(minAmountStr);
        List<Deposit> depositParam = new ImexDepProfitParser().parser(minAmount, TD_UAH_RATE_INDEX, Currency.UAH);

        return depositParam;
    }

    /**
     * Get USD deposit`s params
     *
     * @return USD deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getUSDDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table[width=672]").select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").first();
        String minAmountStr = minAmountEl.text().substring(39, 45).replace(" ", "");
        int minAmount = Integer.parseInt(minAmountStr);
        List<Deposit> depositParam = new ImexDepProfitParser().parser(minAmount, TD_USD_RATE_INDEX, Currency.USD);

        return depositParam;
    }

    /**
     * Get EUR deposit`s params
     *
     * @return EUR deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> getEURDeposit() throws AdapterConnectException {
        Element minAmountEl = con.select("div.about_content table[width=672]").select("tr").
                get(TR_MIN_AMOUNT_INDEX).select("td").first().select("p").first();
        String minAmountStr = minAmountEl.text().substring(57, 63).replace(" ", "");
        int minAmount = Integer.parseInt(minAmountStr);
        List<Deposit> depositParam = new ImexDepProfitParser().parser(minAmount, TD_EUR_RATE_INDEX, Currency.EUR);

        return depositParam;
    }

    /**
     * Get some deposit`s params
     *
     * @param minAmount
     * @param tdRateIndex - index for the rate`s counting
     * @param currency
     * @return some deposit`s params
     * @throws AdapterConnectException
     */
    public List<Deposit> parser(int minAmount, int tdRateIndex, Currency currency) throws AdapterConnectException {
        Pattern p = Pattern.compile("(»|«)");
        Matcher matcher = null;
        List<Deposit> depositParam = new ArrayList<>();
        Deposit deposit = new Deposit();
        Element nameEL = con.select("div.about_content table[width=672]").select("th").first().select("b").get(B_NAME_INDEX);
        matcher = p.matcher(nameEL.text());
        String name = matcher.replaceAll("").trim();

        Element termEL = con.select("div.about_content table[width=672]").select("tr").get(TR_TERM_INDEX).select("td")
                .get(TERM_INDEX);
        String[] StringsWithTerms = termEL.text().split(" ");

        Element rateEL = con.select("div.about_content table[width=672]").select("tr").get(TR_TERM_INDEX).select("td")
                .get(tdRateIndex);

        int term = Integer.parseInt(StringsWithTerms[TERM_INDEX]) * 31;
        double rate = Double.parseDouble(rateEL.text().replace(",", "."));

        deposit.setType(DepositType.Deposit);
        deposit.setDepositRate(rate);
        deposit.setTerm(term);
        deposit.setMinAmount(minAmount);
        deposit.setName(name);
        deposit.setRefill(true);
        deposit.setUrl(DEPOSIT_URL);
        deposit.setState(State.ACTIVE);
        deposit.setCurrency(currency);
        deposit.setBank(bank);
        depositParam.add(deposit);
        return depositParam;
    }
}
